import type { Router } from 'vue-router'
import { useUserStore } from '@/stores/modules'
import { getQueryParam } from '@/utils/index'

export const createRouterGuards = async (router: Router, whiteNameList) => {
  const userInfo = useUserStore()

  console.log(userInfo.token, 'token')

  router.beforeEach(async (to, from, next) => {
    if (userInfo.token) {
      console.log(1)

      next()
    } else {
      if (whiteNameList.includes(to.fullPath)) {
        console.log(2)
        next()
      } else if (userInfo.isBind == '1') {
        console.log(3)
        next()
      } else {
        console.log(4)
        try {
          const code = getQueryParam(to.fullPath, 'code')
          const state = getQueryParam(to.fullPath, 'state')
          console.log(to,'beforeEach');

          if (!code) throw new Error('code为空!')
          await userInfo.getUserInfoAsync(code as string)
          userInfo.SET_QUERY(to.query)
          next({
            replace: true,
            path: userInfo.token ? `/${state || 'dashboard'}` : '/login',
            query: to.query,
          })
        } catch (error) {
          next({
            replace: true,
            path: '/login',
          })
        }
      }
    }
  })

  router.afterEach((to, from, next) => {
    console.log(to, 'afterEach')
  })

  router.onError((err) => {
    console.error(err)
    console.error('路由错误')
  })
}
